package com.cdy.client.netty;

import com.cdy.common.command.Command;
import com.cdy.common.command.UploadCommand;
import com.cdy.common.response.DownloadResponse;
import com.cdy.common.response.Response;
import com.cdy.common.serialize.HessionSerialize;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 客户端解码
 * Created by 陈东一
 * 2019/10/20 0020 19:09
 */
public class ClientDecodeHandler extends ByteToMessageDecoder {
    private final HessionSerialize serialize = new HessionSerialize();
    private final ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byteBuf.writeBytes(in);

        while(true) {
            if (byteBuf.readableBytes() < 4) {
                return;
            }

            int totalLength = byteBuf.readInt();

            if (byteBuf.readableBytes() < totalLength) {
                byteBuf.readerIndex(0);
                return;
            }

            int commandLength = byteBuf.readInt();

            byte[] bytes = new byte[commandLength];
            this.byteBuf.readBytes(bytes);
            Response command = serialize.deserialize(bytes, Response.class);

            if (totalLength > commandLength) {
                ByteBuf fileByte = this.byteBuf.readBytes(totalLength - commandLength);
                if (command instanceof DownloadResponse) {
                    ((DownloadResponse) command).setByteBuf(fileByte);
                }
            }
            out.add(command);
            this.byteBuf.discardReadBytes();
            this.byteBuf.writerIndex(0);
            this.byteBuf.readerIndex(0);
        }
    }
}
